<?php
set_include_path('system'.PATH_SEPARATOR.'templates'.PATH_SEPARATOR.'blast');
require_once('DatabaseUtility.php');
require_once('blast_processing.php');

$stype = $_GET['stype'];
$org = $_GET['org'];
$ref = $_GET['ref'];
$seq = strtoupper($_GET['seq']);
$eval = $_GET['eval'];

$hits = array();
$getref = '&org='.$org.'&ref='.$ref;
$ev = array(1e-100,1e-10,1e-5,0.001,0.1,1,10,100);

if($stype == "pro_b") {
	print_r(pro_blast($seq, $org, $ref, $eval, false));
} else if($stype == "pep_b") {
	print_r(pep_blast($seq, $org, $ref, $eval, false));
}

function pro_blast($seq, $org, $ref, $eval, $bRaw){
	$rData = array();
	$aaRawData = array();
	
	$hits = protein_blast_pre_process($seq, $eval, $org, $ref);

	if(!empty($hits)) {
		openDatabase();
		$query  = 'SELECT id, annotation, latin FROM protein,organism WHERE protein.organism=organism.label AND protein.id IN (';
		foreach($hits as $id => $eval){
			$query .= $id.',';
		}
		$query = trim($query, ",");
		$query .= ');';
		$results = runQuery($query);
		
		foreach($results as $result){
			$protId = $result['id'];
			$button = '<a class="button" href="protein.php?id='.$protId.'&ref='.$ref.'">Details</a>';
			
			$accessions = getXref($protId);
			$desc = '';
			foreach($accessions as $accession){
				$desc .= '<a href="protein.php?id='.$protId.'&ref='.$ref.'">'.$accession.'</a>,&nbsp; ';
			}
			if(!empty($result['annotation'])){
				$desc .= '<br />'.$result['annotation'];
			}
			
			array_push($rData, array(eq($button), eq($hits[$protId]), eq($desc), eq('<i>'.$result['latin'].'</i>')));
			array_push($aaRawData, array('eval' => $hits[$protId], 'acc' => $acc, 'latin' => $result['latin'], 'protId' => $protId));
		}
		closeDatabase();
	}
	
	$rData = '{ "aaData": ['.toJSArray($rData).'] }';
	
	if(!$bRaw) {
		return $rData;
	} else {
		return $aaRawData;
	}
}

function pep_blast($seq, $org, $ref, $eval, $bRaw){
	$rData = array();
	
	$hits = peptide_blast_pre_process($seq, $eval, $org, $ref);
	
	if(!empty($hits)) {
		openDatabase();
		$query  = "SELECT id, annotation, latin FROM protein, organism WHERE protein.organism=organism.label AND protein.id IN (";
		foreach($hits as $idc => $hit){
			$id = explode('.', $idc);
			$id = $id[0];
			$query .= $id.',';
		}
		$query = trim($query, ",");
		$query .= ');';
		$results = runQueryWithKey($query, 'id');
		
		foreach($hits as $idc => $hit){
			$id = explode('.', $idc);
			$protId = $id[0];
			$result = $results[$protId];
			
			$nrseq = $hit["nrseq"];
			$protein = $hit["protein"];
			$xref = implode('&nbsp;&nbsp;', getXrefLink($protId));
			$pepLocation = $hit["location"];
			$eval = $hit["evalue"];
			$queryseq = $hit["queryseq"];
			$querystart = $hit["querystart"];
			$queryend = $hit["queryend"];
			$matchseq = $hit["matchseq"];
			$sbjctseq = $hit["sbjctseq"];
			$sbjctstart = $hit["sbjctstart"];
			$sbjctend = $hit["sbjctend"];
			$sites = $hit['sites'];
			
			$linkformat = str_replace('#', '%23', $nrseq);
			$button = '<a class="button" href="peptide.php?pnrseq='.$linkformat.'&pro='.$protId.'&loc='.$pepLocation.'">Details</a>';
			
			$accessions = getXref($protId);
			$desc = '';
			foreach($accessions as $accession){
				$desc .= '<a href="protein.php?id='.$protId.'&ref='.$ref.'">'.$accession.'</a>,&nbsp; ';
			}
			if(!empty($result['annotation'])){
				$desc .= '<br />'.$result['annotation'];
			}
			
			$alignment = getAlignment($querystart, $queryend, $queryseq, $sbjctseq, $sbjctstart, $sbjctend, $sites, $matchseq, $nrseq, $pepLocation, $getref);

			array_push($rData, array(eq($button), eq($alignment), eq($eval), eq($desc), eq('<i>'.$result['latin'].'</i>')));
		}
		
		closeDatabase();
	}
	
	$rData = '{ "aaData": ['.toJSArray($rData).'] }';
	
	return $rData;
}

function eq($str){ //escape quotes
	return str_replace('"', '\"', $str);
}

function toJSArray($phpArray) {
	$r = '';
	foreach($phpArray as $val){
		$r .= '["' . implode('","', $val) . '"],';
	}
	return  trim($r, ",");
}

function getAlignment($querystart, $queryend, $queryseq, $sbjctseq, $sbjctstart, $sbjctend, $sites, $matchseq, $nrseq, $pepLocation, $getref) {
	return '<table class="alignment" cellspacing="0" cellpadding="0" border="0">'.
	'<tr>'.
		'<td>Query:&nbsp;</td>'.
		'<td><span class="sequence">'.($querystart+1).'&nbsp;</span></td>'.
		'<td><span class="sequence">'.formatPepQuery($queryseq, $sbjctseq, $sites).'&nbsp;'.($queryend+1).'</span></td>'.
	'</tr>'.
	'<tr>'.
		'<td></td>'.
		'<td></td>'.
		'<td><span class="sequence">'.str_replace(" ","&nbsp;",$matchseq).'</span></td>'.
	'</tr>'.
	'<tr>'.
		'<td>Subject:&nbsp;</td>'.
		'<td><span class="sequence">'.($pepLocation+$sbjctstart+1).'&nbsp;</span></td>'.
		'<td><span class="sequence">'.formatPepSubject($sbjctseq, $sites, $getref).'&nbsp'.($pepLocation+$sbjctend+1).'</span></td>'.
	'</tr>'.
	'</table>';
}
function formatPepQuery($seqquery, $seqpep, $sites) {
	$seq = '';
	$len = strlen($seqpep);
	$start = 0;
	foreach($sites as $loc=>$siteid) {
		$loc = indexConvert_gap_excluded($seqpep,$loc);
		if ($loc<0||$loc>=$len) continue;
		$sbst = substr($seqquery,$loc,1);
		if (preg_match("/[stySTY]/",$sbst)) {
			$sbst = '<span class="ui-corner-all phosphosite">'.$sbst.'</span>';
		}
		$seq = $seq.substr($seqquery,$start,$loc-$start).$sbst;
		$start = $loc + 1;
	}
	$seq = $seq.substr($seqquery,$start);
	return $seq;
}
function formatPepSubject($seqpep,$sites,$get) {
	$seq = '';
	$len = strlen($seqpep);
	$start = 0;
	foreach($sites as $loc=>$siteid) {
		$loc = indexConvert_gap_excluded($seqpep,$loc);
		if ($loc<0||$loc>=$len) continue;
		$sbst = '<a href="phosphosite.php?id='.$siteid.$get.'" class="ui-corner-all phosphosite">'.substr($seqpep,$loc,1).'</a>';
		$seq = $seq.substr($seqpep,$start,$loc-$start).$sbst;
		$start = $loc + 1;
	}
	$seq = $seq.substr($seqpep,$start);
	return $seq;
}
function indexConvert_gap_excluded($seq, $index) {
	if ($index<0 || $index>=strlen($seq)) return -1;

	$count = 0;
	for ($i=0; $count<$index; $i++) {
		if ($seq[$i]!='-') {
			$count++;
		}
	}
	
	return $i;
}
?>